# -*- coding: utf-8 -*-
'''
Created on Sep 2, 2019

@author: yl
'''
from PyUeye.Full_Frame import file_name, img_name
import numpy as np
import os
import datetime
now = datetime.datetime.now()


def fit_func(x, a, b, c):
    return a*(x-b)**2 + c
# p= -0.0213125
p= -0.02135
def fit_func_phase(x, q):
    return p*x+q
def fit_func_line(x, p, q):
    return p*x+q

#############
# fs_cam = 575.8  ###USB2.0
# fs_cam = 1370.72 ###USB3.0
# fs_cam = 1860 ###USB3.0 numpy readout
fs_cam = 50 ### Hardware Trigger
####################

Lamda = 633e-9
pix_size = 5.3e-6
V_x, V_y, V_z = 0, 0, 0

img_set = []
hor_phase_centers = []
hor_freq_set = []
hor_f_fit_set = []
hor_phi_fit_set = []

f = open(file_name, 'rb')

f_size = os.fstat(f.fileno()).st_size
frames = []
time_sequence = []
while f.tell() < f_size:
#         print(f.tell())
    frame = np.load(f, allow_pickle=True)
    frames.append(frame[0])
    time_sequence.append(frame[1])

# x_axis = np.linspace(0, len(time_sequence)-1, len(time_sequence))

frames = np.array(frames)
print(frames.shape)

if len(frames.shape) == 4:
    print('file_size: %.1f MB'%(f_size/1e6))
    print('%i frames'%len(frames))
    print('%i lines/frame'%len(frames[0]))
    print('%i pixels/line'%len(frames[0][0]))
    print('%i channels/pixel'%len(frames[0][0][0]))

elif len(frames.shape) == 3:
    print('file_size: %.1fMB'%(f_size/1e6))
    print('%i frames'%len(frames))
    print('1 line/frame')
    print('%i pixels/line'%len(frames[0]))
    print('%i channels/pixel'%len(frames[0][0]))

print('frame rate: %.2f'%fs_cam)
print('record time: %f s'%(len(frames)/fs_cam))

pix_buffer = []
frame_count = 0
for frame in frames:
    frame_count += 1
    for line in frame:
        for pixel in line:
            pixel_value = pixel[0]+256*pixel[1]
            pix_buffer.append(pixel_value)
    print('frame %i'%frame_count)
pix_buffer = np.array(pix_buffer)
pix_buffer = pix_buffer.reshape(len(frames),1024,1280)
print(pix_buffer.shape)

f = open(img_name,'ab')
np.save(f, pix_buffer, allow_pickle=True)


